package com.sx.pipeline.ui.goods.add

import android.Manifest
import android.graphics.BitmapFactory
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ToastUtils
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.lxj.xpopup.XPopup
import com.permissionx.guolindev.PermissionX
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.app.base.CYDataBindingBaseActivity
import com.sx.pipeline.app.config.IntentKey
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.custom.dialog.CustomCommonPicket
import com.sx.pipeline.custom.dialog.MyCityPickerListener
import com.sx.pipeline.custom.dialog.MyCityPickerPopup
import com.sx.pipeline.databinding.ActGoodsAddBinding
import com.sx.pipeline.repos.http.res.ProvincesVO
import com.sx.pipeline.ui.goods.GoodsVM
import com.sx.pipeline.utils.AndroidUtil
import com.sx.pipeline.utils.CompressHelper
import com.sx.pipeline.utils.GlideEngine
import com.sx.pipeline.utils.PermissionHelper


/**
 * @Author: YY
 * @Date: 2022/4/5
 * @Description: 供应商-添加商品
 */
@Route(path = RoutePath.Mine.COMMODITY_ADD)
class GoodsAddActivity :
    CYDataBindingBaseActivity<ActGoodsAddBinding, GoodsVM>(R.layout.act_goods_add),
    View.OnClickListener {
    @JvmField
    @Autowired(name = IntentKey.ID)
    var goodsId: Int? = 0

    @JvmField
    @Autowired(name = IntentKey.TYPE)
    var type: Int? = 0  //1 添加商品  2编辑商品

    override fun initData() {
        super.initData()
        mBinding.setVariable(BR.onClick, this)
        mBinding.titleBar.leftView.setOnClickListener {
            finish()
        }
        initProductImages()
        //获取商品配置数据
        mViewModel.getProduct()
        //获取联系人
        mViewModel.getContacts()
        //默认联系人
        mBinding.etContact.setText(mViewModel.mModel.getUserData()?.userName)
        mBinding.etContactPhone.setText(mViewModel.mModel.getUserData()?.phone)
        when (type) {
            1 -> {
                mBinding.titleBar.title = getString(R.string.txt_add_commodity)

            }
            else -> {
                mBinding.titleBar.title = getString(R.string.txt_edit_commodity)
                mBinding.tvDelete.visibility = View.VISIBLE
                goodsId?.let { mViewModel.getGoodsDetail(it) }
            }
        }
    }

    override fun initViewModel() {
        super.initViewModel()
        //上传的图片
        observe(mViewModel.uploadDataEvent) {
            mBinding.imageProduct.addImage(it)
        }

        //编辑设备 设备数据
        observe(mViewModel.goodsDetailDataEvent) {
            it?.let {
                //设备名称
                mBinding.etGoodsName.setText(it.name)
                //产品型号
                mBinding.etGoodsModel.setText(it.productModel)
                //主要参数
                mBinding.etParam.setText(it.parameter)
                //产品制造厂家
                mBinding.etManufacturer.setText(it.manufacturer)
                //价格
                mBinding.etPrice.setText(it.price)
                //服务区域
                mViewModel.provinceIDField.set(it.provinceId)
                mViewModel.cityIDField.set(it.cityId)
                mViewModel.areaIDField.set(it.areaId)
                mViewModel.longitudeField.set(it.longitude)
                mViewModel.latitudeField.set(it.latitude)
                // 显示地址
                mBinding.tvArea.text = it.addressDetail
                //设备所属单位
                mBinding.etSaleUnit.setText(it.unit)
                //联系人
                mBinding.etContact.setText(it.contact)
                //联系电话
                mBinding.etContactPhone.setText(it.contactPhone)
                //销售分类
                mBinding.tvSaleClass.text = it.salesClass

                if (!TextUtils.isEmpty(it.productImage)) {
                    val imageList = it.productImage.split(",")
                    for (i in imageList) {
                        mBinding.imageProduct.addImage(i)
                    }
                }
            }

        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_principal -> {
                if (mViewModel.taskContactData.size == 0) {
                    ToastUtils.showShort("未获取到数据")
                    return
                }
                val popup = CustomCommonPicket(this, getString(R.string.txt_choose_principal))
                popup.setPickerData(mViewModel.taskContactData)
                popup.setCommonPickerListener { position, data ->
                    mBinding.etContact.setText(data)
                    mBinding.etContactPhone.setText(mViewModel.taskContactPhoneData[position])
                }
                XPopup.Builder(this)
                    .borderRadius(42f)
                    .isDarkTheme(false)
                    .asCustom(popup)
                    .show()
            }
            //选择销售分类
            R.id.tv_sale_class -> {
                if (mViewModel.saleClassData.size == 0) {
                    ToastUtils.showShort("未获取到数据")
                    return
                }
                val popup = CustomCommonPicket(this, getString(R.string.txt_choose_sale_class))
                popup.setPickerData(mViewModel.saleClassData)
                popup.setCommonPickerListener { _, data ->
                    mBinding.tvSaleClass.text = data
                }
                XPopup.Builder(this)
                    .borderRadius(42f)
                    .isDarkTheme(false)
                    .asCustom(popup)
                    .show()
            }
            //选择服务区域
            R.id.tv_area -> {
                //选择服务区域
                showProvincesDialog()
            }
            R.id.tv_submit -> {
                Log.d("resssss", "提交")
                if (type == 1) {
                    //添加设备
                    mViewModel.productAdd(
                        mBinding.etGoodsName.text.toString(),
                        mBinding.etGoodsModel.text.toString(),
                        mBinding.etParam.text.toString(),
                        mBinding.etManufacturer.text.toString(),
                        mBinding.etPrice.text.toString(),
                        mBinding.tvArea.text.toString(),
                        mBinding.etSaleUnit.text.toString(),
                        mBinding.etContact.text.toString(),
                        mBinding.etContactPhone.text.toString(),
                        mBinding.tvSaleClass.text.toString(),
                        mBinding.imageProduct.imagePath
                    )
                } else {
                    //编辑设备
                    goodsId?.let {
                        mViewModel.productEdit(
                            it,
                            mBinding.etGoodsName.text.toString(),
                            mBinding.etGoodsModel.text.toString(),
                            mBinding.etParam.text.toString(),
                            mBinding.etManufacturer.text.toString(),
                            mBinding.etPrice.text.toString(),
                            mBinding.tvArea.text.toString(),
                            mBinding.etSaleUnit.text.toString(),
                            mBinding.etContact.text.toString(),
                            mBinding.etContactPhone.text.toString(),
                            mBinding.tvSaleClass.text.toString(),
                            mBinding.imageProduct.imagePath
                        )
                    }
                }
            }
            R.id.tv_delete -> {
                XPopup.Builder(this)
                    .isDestroyOnDismiss(true)
                    .asConfirm(
                        getString(R.string.hint), getString(R.string.txt_confirm_delete_commodity),
                        getString(R.string.cancel), getString(R.string.confirm),
                        {
                            //删除商品
                            goodsId?.let { mViewModel.deleteProduct(it) }
                        }, null, false
                    ).show()
            }
        }
    }


    //设备图片
    private fun initProductImages() {
        // 上传图片
        mBinding?.imageProduct!!.initAdapter(3, 3)
        mBinding?.imageProduct!!.setImageUploadListener {
            PermissionHelper.requestTip(this,"上次图片需要授权相机和读写权限",object :
                PermissionUtils.SimpleCallback{
                override fun onGranted() {
                    PictureSelector.create(this@GoodsAddActivity)
                        .openGallery(SelectMimeType.ofImage())
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setMaxSelectNum(3 - mBinding.imageProduct.imagePath.size)
                        .forResult(object : OnResultCallbackListener<LocalMedia?> {
                            override fun onResult(result: ArrayList<LocalMedia?>?) {
                                //循环上传图片
                                for (i in 0 until result?.size!!) {
                                    Log.d("okhttp", "" + result[i]?.realPath)
                                    //压缩图片
                                    val inputBitmap = BitmapFactory.decodeFile(result[i]?.realPath)
                                    val compressFile = CompressHelper.compressQuality(
                                        this@GoodsAddActivity, inputBitmap
                                    )
                                    mViewModel.uploadImage(compressFile)
                                }
                            }

                            override fun onCancel() {}
                        })

                }

                override fun onDenied() {
                    ToastUtils.showShort("请授权后再继续操作")
                }
            },Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA)

//            PermissionX.init(this)
//                .permissions(
//                    Manifest.permission.READ_EXTERNAL_STORAGE,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                    Manifest.permission.CAMERA
//                )
//                .onExplainRequestReason { scope, deniedList ->
//                    scope.showRequestReasonDialog(
//                        deniedList,
//                        "核心基础功能基于这些权限,请允许,否则影响app正常使用",
//                        "确认",
//                        "取消"
//                    )
//                }
//                .onForwardToSettings { scope, deniedList ->
//                    scope.showForwardToSettingsDialog(
//                        deniedList,
//                        "您需要手动在“设置”中允许必要的权限",
//                        "确定",
//                        "取消"
//                    )
//                }
//                .request { allGranted, grantedList, deniedList ->
//                    if (allGranted) {
//                        PictureSelector.create(this)
//                            .openGallery(SelectMimeType.ofImage())
//                            .setImageEngine(GlideEngine.createGlideEngine())
//                            .setMaxSelectNum(3 - mBinding.imageProduct.imagePath.size)
//                            .forResult(object : OnResultCallbackListener<LocalMedia?> {
//                                override fun onResult(result: ArrayList<LocalMedia?>?) {
//                                    //循环上传图片
//                                    for (i in 0 until result?.size!!) {
//                                        Log.d("okhttp", "" + result[i]?.realPath)
//                                        //压缩图片
//                                        val inputBitmap = BitmapFactory.decodeFile(result[i]?.realPath)
//                                        val compressFile = CompressHelper.compressQuality(
//                                            this@GoodsAddActivity, inputBitmap
//                                        )
//                                        mViewModel.uploadImage(compressFile)
//                                    }
//                                }
//
//                                override fun onCancel() {}
//                            })
//                    } else {
//                        ToastUtils.showShort(getString(R.string.txt_these_permissions_are_denied))
//                    }
//                }

        }
    }

    /**
     * 省市区选择
     */
    private fun showProvincesDialog() {
        val popup = MyCityPickerPopup(ActivityUtils.getTopActivity())
        popup.setCityPickerListener(object : MyCityPickerListener {
            override fun onCityConfirm(
                provincesVO: ProvincesVO?, cityVO: ProvincesVO?, areaVO: ProvincesVO?,
                province: String?, city: String?, area: String?, v: View?,
            ) {
                mViewModel.provinceIDField.set(provincesVO!!.id.toInt())
                mViewModel.cityIDField.set(cityVO!!.id.toInt())
                mViewModel.areaIDField.set(areaVO!!.id.toInt())
                mViewModel.addressField.set("$province $city $area")
                mViewModel.longitudeField.set(areaVO.center.split(",")[0])
                mViewModel.latitudeField.set(areaVO.center.split(",")[1])
                // 显示地址
                mBinding.tvArea.text = "$province $city $area"
            }

            override fun onCityChange(province: String?, city: String?, area: String?) {

            }
        })
        XPopup.Builder(this).asCustom(popup).show()
    }
}